import mongoose, { Document, Schema } from 'mongoose';

export interface IDeviceData extends Document {
  deviceId: string;
  userId: mongoose.Types.ObjectId;
  timestamp: Date;
  data: {
    temperature?: number;
    humidity?: number;
    battery?: number;
    signal?: number;
    [key: string]: any;
  };
  metadata?: {
    firmwareVersion?: string;
    ipAddress?: string;
    connectionType?: 'wifi' | 'ethernet' | 'cellular';
    [key: string]: any;
  };
}

const deviceDataSchema = new Schema({
  deviceId: {
    type: String,
    required: true,
    index: true
  },
  userId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true
  },
  timestamp: {
    type: Date,
    required: true,
    default: Date.now,
    index: true
  },
  data: {
    type: Schema.Types.Mixed,
    required: true,
    default: {}
  },
  metadata: {
    type: Schema.Types.Mixed,
    default: {}
  }
}, {
  timestamps: true
});

// 创建复合索引
deviceDataSchema.index({ deviceId: 1, timestamp: -1 });
deviceDataSchema.index({ userId: 1, timestamp: -1 });

// 检查模型是否已经存在，如果存在则使用现有模型
export const DeviceData = mongoose.models.DeviceData || mongoose.model<IDeviceData>('DeviceData', deviceDataSchema); 